package comqyf.nacoscloudzookeeper.controller;


import comqyf.nacoscloudzookeeper.repository.ZooRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Random;


@Slf4j
@RestController
public class ZooController {

    @Autowired
    private ZooRepository zooRepository;

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "createNode")
    public String createNode(String nodeName, String nodeValue){
        try {
            zooRepository.createNode(nodeName, nodeValue);
            return "success";
        } catch (Exception e) {
            log.error("getList func fail message:{}", e.getMessage());
            return null;
        }
    }

    @RequestMapping(value = "deleteNode")
    public String deleteNode(String nodeName){
        try {
            zooRepository.delNode(nodeName);
            return "success";
        } catch (Exception e) {
            log.error("deleteNode func fail message:{}", e.getMessage());
            return null;
        }
    }

    @RequestMapping(value = "getNodes")
    public List<String> getNodes(){
        try {
            List<String> nodes = zooRepository.getChildPaths();
            return nodes;
        } catch (Exception e) {
            log.error("getNodes func fail message:{}", e.getMessage());
            return null;
        }
    }

    @RequestMapping(value = "getData")
    public Map<String, String> getData(){
        try {
            Map<String, String> data = zooRepository.getChildValues();
            return data;
        } catch (Exception e) {
            log.error("getData func fail message:{}", e.getMessage());
            return null;
        }
    }

    @RequestMapping(value = "/hello")
    public String hello(){
        List<ServiceInstance> instances = client.getInstances("zookeeper");
        ServiceInstance instance = instances.get(new Random().nextInt(instances.size()));
        return "Hello World: " + instance.getServiceId() + ":" + instance
                .getHost() + ":" + instance.getPort();
    }

}
